package com.example.seabedmusic.views;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.SongAdapter;
import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.HotSong;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.presenter.MusicPresenter;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.PlaylistManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DailyRecommendActivity extends AppCompatActivity implements MusicContract.IMusicView {

    private ImageView backIv;
    private ImageView dailyCoverIv;
    private TextView recommendNameTv;
    private TextView songCountTv;
    private RecyclerView dailySongList;
    private ProgressBar loadingPb;
    private LinearLayout continuePlayingLayout;
    private TextView currentSongTv;

    private SongAdapter songAdapter;
    private List<Song> songList = new ArrayList<>();
    private MusicContract.IMusicPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily_recommend);

        initViews();
        setupClickListeners();
        setupRecyclerView();

        // 初始化 Presenter
        mPresenter = new MusicPresenter(this, this);

        // 加载每日推荐数据 - 从热歌榜随机选择16首
        loadDailyRecommendations();
    }

    private void initViews() {
        backIv = findViewById(R.id.back_iv);
        dailyCoverIv = findViewById(R.id.daily_cover_iv);
        recommendNameTv = findViewById(R.id.recommend_name_tv);
        songCountTv = findViewById(R.id.song_count_tv);
        dailySongList = findViewById(R.id.daily_song_list);
        loadingPb = findViewById(R.id.loading_pb);
        continuePlayingLayout = findViewById(R.id.continue_playing_layout);
        currentSongTv = findViewById(R.id.current_song_tv);
    }

    private void setupClickListeners() {
        // 返回按钮点击事件
        backIv.setOnClickListener(v -> finish());
    }

    private void loadDailyRecommendations() {
        // 显示加载进度条
        loadingPb.setVisibility(View.VISIBLE);
        dailySongList.setVisibility(View.GONE);

        // 使用 Presenter 获取热歌榜数据，然后从中随机选择16首
        // 这里直接调用 getHot() 方法，因为 getHotSongs() 内部也是调用 getHot()
        mPresenter.getDaily();
    }

    private void playSong(Song song) {
        // 实现播放歌曲的逻辑
        // 这里可以更新继续播放的提示
        continuePlayingLayout.setVisibility(View.VISIBLE);
        currentSongTv.setText(song.getTitle());

        // TODO: 实现具体的播放逻辑
        showToast("播放: " + song.getTitle());
    }

    /* =============== MusicContract.IMusicView 接口实现 =============== */


    @Override
    public void showRecent(List<Song> songs) {
        // 在这个页面不需要实现
    }

    @Override
    public void showToast(String msg) {
        android.widget.Toast.makeText(this, msg, android.widget.Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {
        // 可以在这里显示额外的加载提示
    }

    @Override
    public void hideLoading() {
        // 可以在这里隐藏额外的加载提示
    }

    /**
     * 从歌曲列表中随机选择指定数量的歌曲
     * @param allSongs 所有歌曲列表
     * @param count 需要选择的歌曲数量
     * @return 随机选择的歌曲列表
     */
    private List<Song> getRandomSongs(List<Song> allSongs, int count) {
        List<Song> randomSongs = new ArrayList<>();

        if (allSongs == null || allSongs.isEmpty()) {
            return randomSongs;
        }

        // 如果歌曲数量少于需要的数量，返回所有歌曲
        if (allSongs.size() <= count) {
            return new ArrayList<>(allSongs);
        }

        // 随机选择指定数量的歌曲
        List<Song> tempList = new ArrayList<>(allSongs);
        Collections.shuffle(tempList); // 随机打乱顺序

        for (int i = 0; i < count; i++) {
            randomSongs.add(tempList.get(i));
        }

        return randomSongs;
    }

    private void checkCurrentPlaying() {
        // 检查是否有正在播放的歌曲
        // 这里需要根据你的播放器状态来实现
        // 暂时设置为不显示继续播放提示
        continuePlayingLayout.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            // 清理资源
        }
    }




    private void setupRecyclerView() {
        songAdapter = new SongAdapter(songList);
        dailySongList.setLayoutManager(new LinearLayoutManager(this));
        dailySongList.setAdapter(songAdapter);

//        // 设置歌曲点击监听器
//        songAdapter.setOnHotSongItemClickListener(new SongAdapter.OnHotSongItemClickListener() {
//            @Override
//            public void onHotSongItemClick(int position, Song song) {
//                // 点击歌曲项，跳转到播放页面
//                playSongInPlayer(position, song);
//            }
//
//            @Override
//            public void onHotSongMoreClick(int position, Song song) {
//                // 显示更多操作菜单（可选）
//                showSongOptionsMenu(position, song);
//            }
//        });
    }

    /**
     * 跳转到播放页面播放歌曲
     */
    private void playSongInPlayer(int position, Song song) {
        try {
            // 将 Song 转换为 HotSong（为了与现有的播放器兼容）
            HotSong hotSong = convertSongToHotSong(song, position);

            // 创建歌曲列表（将所有的 Song 转换为 HotSong）
            ArrayList<HotSong> hotSongList = new ArrayList<>();
            for (int i = 0; i < songList.size(); i++) {
                hotSongList.add(convertSongToHotSong(songList.get(i), i));
            }

            // 创建 Intent 跳转到 HotMusicPlayerActivity
            Intent intent = new Intent(this, HotMusicPlayerActivity.class);

            // 传递当前歌曲信息
            intent.putExtra("song_title", hotSong.getName());
            intent.putExtra("song_artist", hotSong.getAuthor());
            intent.putExtra("song_cover", hotSong.getCover());
            intent.putExtra("song_album", hotSong.getAlbum());
            intent.putExtra("song_hash", hotSong.getHash());
            intent.putExtra("song_rank", hotSong.getRank());
            intent.putExtra("current_position", position);

            // 传递整个歌曲列表
            intent.putParcelableArrayListExtra("hot_song_list", hotSongList);

            // 启动播放页面
            startActivity(intent);

            // 显示播放提示
            showToast("正在播放: " + song.getTitle());

        } catch (Exception e) {
            Log.e("DailyRecommend", "跳转播放页面失败", e);
            showToast("播放失败，请重试");
        }
    }

    /**
     * 将 Song 对象转换为 HotSong 对象
     */
    private HotSong convertSongToHotSong(Song song, int position) {
        HotSong hotSong = new HotSong();
        hotSong.setId(song.getId() != null ? song.getId() : String.valueOf(System.currentTimeMillis()));
        hotSong.setName(song.getTitle());
        hotSong.setAuthor(song.getArtist());
        hotSong.setCover(song.getCover());
        hotSong.setAlbum(song.getAlbum() != null ? song.getAlbum() : "每日推荐");
        hotSong.setHash(extractHashFromUrl(song.getUrl())); // 从URL中提取hash
        hotSong.setRank(position + 1); // 使用位置作为排名
        hotSong.setUrl(song.getUrl());

        return hotSong;
    }

    /**
     * 从歌曲URL中提取hash值
     */
    private String extractHashFromUrl(String url) {
        if (url != null && url.startsWith("kugou_hash:")) {
            return url.substring("kugou_hash:".length());
        }
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 显示歌曲操作菜单
     */
    private void showSongOptionsMenu(int position, Song song) {
        // 创建选项菜单
        String[] options = {"添加到我喜欢", "添加到歌单", "下载到本地"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(song.getTitle());
        builder.setItems(options, (dialog, which) -> {
            switch (which) {
                case 0: // 添加到我喜欢
                    addToFavorites(song);
                    break;
                case 1: // 添加到歌单
                    addToPlaylist(song);
                    break;
                case 2: // 下载到本地
                    downloadSong(song);
                    break;
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 添加到我喜欢
     */
    private void addToFavorites(Song song) {
        try {
            PlaylistManager playlistManager = PlaylistManager.getInstance();
            boolean success = playlistManager.addToFavorite(song);
            if (success) {
                showToast("已添加到我喜欢");
            } else {
                showToast("已在我喜欢中");
            }
        } catch (Exception e) {
            Log.e("DailyRecommend", "添加到我喜欢失败", e);
            showToast("添加失败");
        }
    }

    /**
     * 添加到歌单
     */
    private void addToPlaylist(Song song) {
        // 这里可以实现歌单选择逻辑
        showToast("添加到歌单功能开发中");
    }

    /**
     * 下载歌曲到本地
     */
    private void downloadSong(Song song) {
        try {
            LocalMusicManager localMusicManager = LocalMusicManager.getInstance(this);
            boolean success = localMusicManager.addSongToLocal(song);
            if (success) {
                showToast("已下载到本地音乐");
            } else {
                showToast("歌曲已在本地音乐中");
            }
        } catch (Exception e) {
            Log.e("DailyRecommend", "下载歌曲失败", e);
            showToast("下载失败");
        }
    }

    // 在 showSongs 方法中添加日志，方便调试
    @Override
    public void showSongs(List<Song> songs) {
        // 隐藏加载进度条
        loadingPb.setVisibility(View.GONE);

        // 从所有热歌中随机选择16首
        List<Song> randomSongs = getRandomSongs(songs, 16);

        // 更新歌曲列表
        songList.clear();
        songList.addAll(randomSongs);
        songAdapter.notifyDataSetChanged();

        // 显示歌曲列表
        dailySongList.setVisibility(View.VISIBLE);

        // 更新歌曲数量统计
        songCountTv.setText("共 " + songList.size() + " 首推荐歌曲");

        // 检查是否有正在播放的歌曲
        checkCurrentPlaying();

        // 显示成功提示
        if (!songList.isEmpty()) {
            showToast("为您推荐 " + songList.size() + " 首热门歌曲");

            // 调试信息：打印前3首歌曲信息
            for (int i = 0; i < Math.min(3, songList.size()); i++) {
                Song song = songList.get(i);
                Log.d("DailyRecommend", "推荐歌曲 " + (i + 1) + ": " +
                        song.getTitle() + " - " + song.getArtist() +
                        " URL: " + song.getUrl());
            }
        }
    }
}